#ifndef _THREAD_H_
#define _THREAD_H_

#include <iostream>
#include <pthread.h>
#include <string>
#include <cstdio>
#include <cstring>
#include <functional>

namespace ThreadModlue
{
    static uint32_t number = 1;

    template <typename T>
    class Thread
    {
        using func_t = std::function<void()>; // 暂时这样写
    private:
        void EnableDetach()
        {
            _isdetach = true;
        }
        void EnableRunning()
        {
            _isrunning = true;
        }
        static void *Routine(void *args) // 属于类内成员函数，默认包含this指针！
        {
            Thread<T> *self = static_cast<Thread *>(args);
            self->EnableRunning();

            if (self->_isdetach)
                self->Deatach();
            self->_func(self->_data); // 回调处理
            return nullptr;
        }
        // bug
    public:
        Thread(func_t func, T data)
            : _tid(0),
              _isdetach(false),
              _isrunning(false),
              res(nullptr),
              _func(func),
              _data(data)
        {
            _name = "thread-" + std::to_string(number++);
        }
        void Deatach()
        {
            if (_isdetach)
                return;
            if (_isrunning)
                pthread_detach(_tid);
            EnableRunning();
        }
        bool Start()
        {
            if (_isrunning)
                return false;
            int n = pthread_create(&_tid, nullptr, Routine, this);
            if (n != 0)
            {
               
                return false;
            }
            else
            {
            }
            return true;
        }
        bool Stop()
        {
            if (_isrunning)
            {
                int n = pthread_cancel(_tid);
                if (n != 0)
                {
                    
                    return false;
                }
            }
            else
            {
                _isrunning = false;
                std::cout << _name << "stop" << std::endl;
                return true;
            }
            return false;
        }
        void Join()
        {
            if (_isdetach)
            {
                return;
            }

            int n = pthread_join(_tid, &res);
            if (n != 0)
            {
                
            }
            else
            {

            }
        }
        ~Thread() {}

    private:
        pthread_t _tid;
        std::string _name;
        bool _isdetach;
        bool _isrunning;
        void *res;
        func_t _func;
        T _data;
    };
}

#endif